package top.jandmla.excel.controller;


import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import top.jandmla.excel.bean.User;
import top.jandmla.excel.util.result.BaseResult;

@RestController
@RequestMapping("common")
public class CommonController {


    /**
     * 权限不够，拦截信息
     * @return 拦截信息
     */
    @RequestMapping("/error403")
    public BaseResult<String> errorTo403(){
        return BaseResult.fail(1,"你没有权限操作,请联系管理员！");
    }

    /**
     * 登录成功
     * @return 登录成功，提示信息
     */
    @PostMapping("/success")
    public BaseResult<String> successToLogin(){
        return BaseResult.success("登录成功！！ 请继续操作！");
    }

    /**
     * 登录方法
     * @param user 用户信息
     * @return 登录结果
     */
    @PostMapping("/login")
    public BaseResult<String> login(@RequestBody User user){
        if (user != null && !StringUtils.isEmpty(user.getUserName()) && !StringUtils.isEmpty(user.getPassword())){
            Subject subject = SecurityUtils.getSubject();
            if (user != null && !StringUtils.isEmpty(user.getUserName()) && !StringUtils.isEmpty(user.getPassword())){
                UsernamePasswordToken token = new UsernamePasswordToken(user.getUserName(),user.getPassword());
                try {
                    subject.login(token);
                    return BaseResult.success(user.getUserName()+"登录成功！");
                }catch (UnknownAccountException e){
                    return BaseResult.fail(1,"用户名错误！");
                }catch (IncorrectCredentialsException e){
                    return BaseResult.fail(1,"密码错误！");
                }
            }
        }
        return BaseResult.fail(1,"账号密码输入不合法！！");
    }

    /**
     * 没有登录时，拦截方法
     * @return 拦截信息
     */
    @RequestMapping("/toLogin")
    public BaseResult<String> toLogin(){
        return BaseResult.fail(1,"还没有登录呢！");
    }

    @PostMapping("logout")
    public BaseResult<String> logout(){
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        return BaseResult.success("退出成功，欢迎下次登录！");
    }




}
